package com.stars.easyms.monitor.config;

import com.stars.easyms.monitor.handler.EasyMsRequestMappingHandlerMapping;
import com.stars.easyms.monitor.MonitorRequestHandler;
import com.stars.easyms.base.util.ApplicationContextHolder;
import com.stars.easyms.monitor.impl.EasyMsMonitorRequestHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.ApplicationContext;

import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * <p>className: EasyMsMonitorRequestMappingInitializer</p>
 * <p>description: EasyMs监控的请求映射初始化类</p>
 *
 * @author guoguifang
 * @date 2019-11-20 11:43
 * @since 1.4.0
 */
@Slf4j
final class EasyMsMonitorRequestMappingInitializer {

    private static final AtomicBoolean INITIALIZED = new AtomicBoolean(false);

    void init() {
        if (INITIALIZED.compareAndSet(false, true)) {
            // 初始化RequestMapping处理类
            ApplicationContext applicationContext = ApplicationContextHolder.getApplicationContext();
            DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) applicationContext.getAutowireCapableBeanFactory();
            EasyMsRequestMappingHandlerMapping easyMsRequestMappingHandlerMapping = new EasyMsRequestMappingHandlerMapping(applicationContext);
            easyMsRequestMappingHandlerMapping.detectHandlerMethods(new EasyMsMonitorRequestHandler());
            getEasyMsMonitorRequestHandlerList().forEach(easyMsRequestMappingHandlerMapping::detectHandlerMethods);
            defaultListableBeanFactory.registerSingleton("easyMsRequestMappingHandlerMapping", easyMsRequestMappingHandlerMapping);
        }
    }

    private List<MonitorRequestHandler> getEasyMsMonitorRequestHandlerList() {
        List<MonitorRequestHandler> easyMsMonitorRequestHandlerArrayList = new ArrayList<>();
        try {
            // 获取所有的实现了EasyMsMonitorRequestHandler接口的类
            ServiceLoader<MonitorRequestHandler> serviceLoader = ServiceLoader.load(MonitorRequestHandler.class);
            for (MonitorRequestHandler easyMsMonitorRequestHandler : serviceLoader) {
                log.info("Found {} EasyMsMonitorRequestHandler : {}!", easyMsMonitorRequestHandler.getModuleName(),
                        easyMsMonitorRequestHandler.getIndexUrl());
                easyMsMonitorRequestHandlerArrayList.add(easyMsMonitorRequestHandler);
            }
        } catch (Exception ex) {
            log.error("Initialization EasyMsMonitorRequestHandler failed!", ex);
        }
        return easyMsMonitorRequestHandlerArrayList;
    }
}